using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

// 泛型工厂类
public class Factory<T, D> where T : BaseEffect<D> where D : DataBase, new()
{
    private static Dictionary<string, Type> typeDictionary;
    private static bool isInit => typeDictionary != null;
    private static void Init()
    {
        if (isInit) return;
        Debug.Log($"初始化 {typeof(T).Name} 脚本");

        var types = Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsInterface && myType.IsSubclassOf(typeof(T)));

        typeDictionary = new Dictionary<string, Type>();

        foreach (var type in types)
        {
            // 使用 new() 约束来创建 D 的实例
            D dataInstance = new D();
            BaseEffect<D> tempEffect = Activator.CreateInstance(type, dataInstance) as BaseEffect<D>;
            if (tempEffect != null)
            {
                Debug.Log(tempEffect.Name);
                //类名来注册具体类
                typeDictionary.Add(tempEffect.Name, type);
            }
        }
    }

    public static T GetEffect(string effectType, D data)
    {
        Init();
        if (typeDictionary.ContainsKey(effectType))
        {
            Type type = typeDictionary[effectType];
            try
            {
                var effectInstance = Activator.CreateInstance(type, data) as T;
                return effectInstance;
            }
            catch (Exception ex)
            {
                Debug.LogError($"无法创建实例 {effectType}: {ex.Message}");
            }
        }
        else
        {
            Debug.LogWarning($"未找到类型 {effectType}");
        }
        return default;
    }

    public static IEnumerable<string> GetNames()
    {
        Init();
        return typeDictionary.Keys;
    }
}

// 基类
public abstract class BaseEffect<D> where D : DataBase
{
    public abstract string Name { get; }
    public abstract D Data { get; set; }

     protected  BaseEffect(D data)
    {
        this.Data = data;
    }
}

// 数据基类
public abstract class DataBase
{
    // 可以在这里添加一些通用的属性，如 ID、名称等
    public int Id { get; set; }
    public string Name { get; set; }

    public string Type { get; set; }
}
/// <summary>
/// 工厂管理
/// </summary>
/// <typeparam name="T">具体的能力类型</typeparam>
/// <typeparam name="D">数据类型</typeparam>
public class FactoryManger<T,D> where T: BaseEffect<D> where D : DataBase, new()
{
    // 使用字典来存储实例，键为 ID 或名称
    private Dictionary<int, T> instanceDictById = new Dictionary<int, T>();
    private Dictionary<string, T> instanceDictByName = new Dictionary<string, T>();

    public List<D> dataList = new List<D>();
    public List<T> instanceList = new List<T>();
    //  public string path;

    public virtual void LoadJson(string path)
    {
        Addressables.LoadAssetAsync<TextAsset>(path).Completed += OnJsonLoaded;
    }

    protected virtual void OnJsonLoaded(AsyncOperationHandle<TextAsset> handle)
    {
        if (handle.Status == AsyncOperationStatus.Succeeded)
        {
            TextAsset jsonAsset = handle.Result;
            string json = jsonAsset.text;

            using (var reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();
                dataList = serializer.Deserialize<List<D>>(reader);  // 流式解析JSON
            }

            foreach (var data in dataList)
            {
                GrantInstance(data.Id);
            }
        }
        else
        {
            Debug.LogError("Failed to load JSON: " + handle);
        }
    }

    protected virtual void GrantInstance(int id)
    {
        var data = dataList.Find(r => r.Id == id);
        var instance = Factory<T, D>.GetEffect(data.Type, data);
        instanceDictById.TryAdd(id, instance);
        instanceDictByName.TryAdd(data.Name, instance);

        if (!instanceList.Contains(instance))
        {
            instanceList.Add(instance);
        }
    }

    public T GetInstance(int id)
    {
        if (instanceDictById.TryGetValue(id, out T instance))
        {
            return instance;
        }
        return null;
    }

    public T GetInstance(string name)
    {
        if (instanceDictByName.TryGetValue(name, out T instance))
        {
            return instance;
        }
        return null;
    }
}


public class DataManager<D> where D : DataBase
{
    private List<D> dataList = new List<D>();

    private Dictionary<int, D> dicData = new Dictionary<int, D>();

    public virtual void LoadJson(string path)
    {
        Addressables.LoadAssetAsync<TextAsset>(path).Completed += OnJsonLoaded;
    }

    protected virtual void OnJsonLoaded(AsyncOperationHandle<TextAsset> handle)
    {
        if (handle.Status == AsyncOperationStatus.Succeeded)
        {
            TextAsset jsonAsset = handle.Result;
            string json = jsonAsset.text;

            using (var reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();
                dataList = serializer.Deserialize<List<D>>(reader);  // 流式解析JSON
            }
            foreach (var data in dataList)
            {
                dicData.TryAdd(data.Id, data);
            }

        }
        else
        {
            Debug.LogError("Failed to load JSON: " + handle);
        }
    }

    public D GetData(int id)
    {
        if (dicData.TryGetValue(id, out D instance))
        {
            return instance;
        }
        return null;
    }

}